"use strict";
// 日志中间件
var C = require('../../config/index');
var logstash = require('./logstash.js');
var debugLog = require('../../o2o/common/function.js').debugLog;
var redisClientDb1 = require('../../common/function.js').redisClientDb1;
var __logKey = 'logstash:v1';
//var __logKey2 = 'logstash:article';
//var logAnalyzer = require('../common/logFlow/logAnalyzer.js');

module.exports = function () {
  try {
    var logInfo = {};
    logInfo.url = decodeURIComponent(this.originalUrl);
    logInfo.method = this.req.method;
    logInfo['X-Response-Time'] = this['X-Response-Time'];
    logInfo.agent = 'api';
    logInfo.startAt = this.startAt;
    // /foo/bar/goo => cate=foo,goo=cmd
    var match = logInfo.url.match(/\/([^\/]*)\/([^\/]*)\/([^\/\?]*).*/);
    logInfo.cate = match && match[1];
    logInfo.cmd = match && match[3];
    logInfo.fromIp = this.ip;
    logInfo.params = {};
    var names = ['apiVer', 'apiVerNum', 'head_mark', 'device_id', 'app_ver_arr', 'loginStatus'];
    if (this.I) {
      for (var key of Object.keys(this.I)) {
        if (names.indexOf(key) >= 0) logInfo[key] = this.I[key];
        else logInfo.params[key] = this.I[key];
      }
    }
    debugLog(' [debug] logInfo ' + JSON.stringify(logInfo));
    debugLog(' [debug] request ' + JSON.stringify(this));
    debugLog(' [debug] response ' + JSON.stringify(this.response._body));
    // response
    var body = this.response._body;
    logInfo.resStatus = body && (body.status || -1);
    //console.log(' [debug] logInfo',JSON.stringify(logInfo));
    //if (C.env === 'development' || C.env === 'test') {
    // TODO push to redis
    //console.log(' [debug] push to redis');
    redisClientDb1.lpush(__logKey, JSON.stringify(logInfo), function (err, res) {
      if (err) debugLog(' [debug] error: save to redis error ' + err);
      //else console.log(' [debug] success: save to redis');
    });
    //}

    logstash.articleAuto(logInfo, this.response._body);

    //
    //// analyzer
    //var analyzeRes = logAnalyzer(logInfo, JSON.parse(body));
    //if (analyzeRes.match && analyzeRes.succ) {
    //  debugLog('[debug] logAnalyze_match', JSON.stringify(analyzeRes.logstash));
    //  //should save
    //  redisClientDb1.lpush(__logKey2, JSON.stringify(analyzeRes.logstash));
    //  redisClientDb1.publish(__logKey2, 'new');
    //  //redisClientDb1.incr('logstash:count_new_way');
    //} else {
    //  debugLog('[debug] logAnalyze_unmatch', JSON.stringify(analyzeRes));
    //}
  } catch (ex) {
    debugLog(' [debug] logstash_error :' + ex);
  }
};